package gameSite;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateItem
 */
@WebServlet("/UpdateItem")
public class UpdateItem extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Connection conn;
	Statement stmt = null;
	ResultSet rs = null;    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateItem() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.print("Do Post");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String result = updateItem(request);
		
		PrintWriter out = response.getWriter();
		out.print(result);
	}
	
	protected String updateItem(HttpServletRequest request){
		String sql, result="Operation Failed";
		int type = Integer.parseInt(request.getParameter("type"));
		
		Product inventory = new Product();
		inventory.setGameName(request.getParameter("itemName"));
		inventory.setTypeOFGame(request.getParameter("category"));
		inventory.setConsole(request.getParameter("console"));
		inventory.setDetails(request.getParameter("description"));
		inventory.setPrice(Double.parseDouble(request.getParameter("price")));
		inventory.setImage(request.getParameter("image"));
		inventory.setNumberOfProducts(Integer.parseInt(request.getParameter("availability")));
		if(type==2){
			int id = Integer.parseInt(request.getParameter("itemID"));
			inventory.setProductID(id);
			sql = "UPDATE Products join Inventory on Products.productID = Inventory.productID SET gameName ='"+ inventory.getGameName() +
					"', typeOfGame='"+inventory.getTypeOfGame()+ "', console='"+inventory.getConsole()+"', details='"+inventory.getDetails()+
					"', price="+inventory.getPrice()+ ", image='"+inventory.getImage()+"', numberOfProducts="+inventory.getNumberOfProducts()+
					" where Products.productID="+inventory.getProductID();
			System.out.println(sql);
			try{ 
			stmt = RemoteConnection.getConnection().createStatement();
			 stmt.executeUpdate(sql);
			 result = "Product has been updated";
			 	 
		      stmt.close();
		      RemoteConnection.closeConnection();
		      return result;		      
			}
			catch(SQLException se){
			      //Handle errors for JDBC
			      se.printStackTrace();
			}
		}
		else {
			sql = "INSERT  INTO Products (gameName, typeOfGame, console, details, price, image) VALUES ('"+ inventory.getGameName() +
					"', '"+inventory.getTypeOfGame()+ "','"+inventory.getConsole()+"', '"+inventory.getDetails()+"', "
					+inventory.getPrice()+ ", '"+inventory.getImage()+"')";
			System.out.println(sql);
			try{ 
				stmt = RemoteConnection.getConnection().createStatement();
				stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
				
				rs = stmt.getGeneratedKeys();
		        if (rs.next()) {
		            int productID = rs.getInt(1);
		            sql = "INSERT INTO Inventory (productID, numberOfProducts) VALUES ("
		            		+productID+ "," + inventory.getNumberOfProducts() + ")";
		            stmt = RemoteConnection.getConnection().createStatement();
		            if(stmt.executeUpdate(sql)==1){
		            	result = "Item successfully added";
		            }
		        } 
		        
			 rs.close();
		      stmt.close();
		      RemoteConnection.closeConnection();
		      return result;
			      
		}
		catch(SQLException se){
		      //Handle errors for JDBC
		      se.printStackTrace();
		   }
		}
		return null;
		
	}

}
